package com.example.makerspace.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.makerspace.domain.ApplicationV2DO;
import com.example.makerspace.domain.CompetitionParentDO;
import com.example.makerspace.domain.TaskDO;
import com.example.makerspace.dto.PageResult;
import com.example.makerspace.dto.Pagination;
import com.example.makerspace.dto.Result;
import com.example.makerspace.dto.ValidateCodeDTO;
import com.example.makerspace.dto.competition.CompetitionParentDTO;
import com.example.makerspace.mapper.ApplicationMapper;
import com.example.makerspace.mapper.ApplicationV2Mapper;
import com.example.makerspace.mapper.CompetitionMapper;
import com.example.makerspace.mapper.CompetitionParentMapper;
import com.example.makerspace.service.CompetitionParentService;
import com.example.makerspace.utils.FileUtils;
import com.example.makerspace.utils.ValidateCodeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

import static com.example.makerspace.enums.ResultCodeEnum.APPLICATION_EXIST;
import static com.example.makerspace.enums.ResultCodeEnum.NOT_ALLOWED_STATUS;

@Service
public class CompetitionParentServiceImpl implements CompetitionParentService {
    @Autowired
    private CompetitionParentMapper competitionParentMapper;
    @Autowired
    private CompetitionMapper competitionMapper;
    @Autowired
    private ApplicationV2Mapper applicationV2Mapper;
    private final static String RESOURCE_PATH_PREFIX = "resource/";
  private  final  static  String   testHttpPrefix="https://119.45.199.13:3035/static/";
   private  final  static  String  devHttpPrefix="https://nism.ytcata.com:443/static/";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result create(CompetitionParentDTO competitionParentDTO) {

        CompetitionParentDO competitionParentDO = new CompetitionParentDO();
        if (competitionParentDTO.getMark() != null && competitionParentDTO.getMark()) {
            competitionParentDO.setMark(false);
            competitionParentMapper.update(competitionParentDO, new QueryWrapper<CompetitionParentDO>().eq("mark", true));
        }
        String path = FileUtils.saveMultipartFile(competitionParentDTO.getImage(),
                FileUtils.staticPath + "resource/" + "competitionParent");
        competitionParentDO.setTitle(competitionParentDTO.getTitle());
        competitionParentDO.setImage(path);
        competitionParentDO.setInfo(competitionParentDTO.getInfo());
        competitionParentDO.setBriefInfo(competitionParentDTO.getBriefInfo());
        competitionParentDO.setOrganizer(competitionParentDTO.getOrganizer());
        competitionParentDO.setMark(competitionParentDTO.getMark());
        competitionParentDO.setStartTime(competitionParentDTO.getStartTime());
        competitionParentDO.setEndTime(competitionParentDTO.getEndTime());
        competitionParentDO.setApplicationEndTime(competitionParentDTO.getApplicationEndTime());
        competitionParentDO.setApplicationStartTime(competitionParentDTO.getApplicationStartTime());
        competitionParentDO.setWorkTime(competitionParentDTO.getWorkTime());
        competitionParentDO.setQuittingTime(competitionParentDTO.getQuittingTime());
        competitionParentDO.setPhoneNumber(competitionParentDTO.getPhoneNumber());
        competitionParentMapper.insert(competitionParentDO);
        List<CompetitionParentDO> competitionParentDOS = competitionParentMapper.selectList(new QueryWrapper<CompetitionParentDO>().eq("mark", true));
        if (competitionParentDOS.size() == 0) {
            //如何无首页展示记录，更新为首页展示
            competitionParentDO.setMark(true);
            competitionParentMapper.updateById(competitionParentDO);
        }
        return Result.success();
    }

    @Override
    public Result query(CompetitionParentDTO competitionParentDTO) {
        QueryWrapper<CompetitionParentDO> queryWrapper = new QueryWrapper<>();
        if (competitionParentDTO.getTitle() != null) {
            queryWrapper.like("title", competitionParentDTO.getTitle());
        }
        if (competitionParentDTO.getMark() != null) {
            queryWrapper.eq("mark", competitionParentDTO.getMark());
        }
        queryWrapper.orderByAsc("start_time");
        Page<CompetitionParentDO> page = new Page<>(competitionParentDTO.getPagination().getPageNum(), competitionParentDTO.getPagination().getSize());
        Page<CompetitionParentDO> competitionParentDOPage = competitionParentMapper.selectPage(page, queryWrapper);
        PageResult pageResult = PageResult.success();
        Pagination pagination = Pagination.builder()
                .size(page.getSize())
                .pageNum(competitionParentDTO.getPagination().getPageNum())
                .total(competitionParentDOPage.getTotal())
                .totalPages(competitionParentDOPage.getPages())
                .build();
        pageResult.setPagination(pagination);

        for (CompetitionParentDO record : competitionParentDOPage.getRecords()) {
            Integer showNumber = (Integer) redisTemplate.opsForValue().get("competitionParent-" + record.getId());
            record.setShowNumber(showNumber);
        }
        pageResult.setObj(competitionParentDOPage.getRecords());
        return pageResult;
    }

    @Override
    public Result delete(Integer id) {
        CompetitionParentDO competitionParentDO = competitionParentMapper.selectById(id);
        if (competitionParentDO.getMark()) {
            return Result.error(NOT_ALLOWED_STATUS);
        }
        QueryWrapper<ApplicationV2DO> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("competition_parent_id", id);
        List<ApplicationV2DO> applicationV2DOS = applicationV2Mapper.selectList(objectQueryWrapper);
        if (applicationV2DOS.size() > 0) {
            return Result.error(APPLICATION_EXIST);
        }
        competitionParentMapper.deleteById(id);
        return Result.success();
    }

    @Override
    public Result update(CompetitionParentDTO competitionParentDTO) {
        CompetitionParentDO competitionParentDO = new CompetitionParentDO();
        BeanUtils.copyProperties(competitionParentDTO,competitionParentDO);
        String image= ValidateCodeUtils.generateCode(4);
        if(!ObjectUtils.isEmpty(competitionParentDTO.getImage())){
            String imagePath = FileUtils.saveMultipartFile2(competitionParentDTO.getImage(), devHttpPrefix + RESOURCE_PATH_PREFIX + image,
                    FileUtils.staticPath + RESOURCE_PATH_PREFIX+image);
            competitionParentDO.setImage(imagePath);
        }
        competitionParentMapper.updateById(competitionParentDO);
        return  Result.success();
    }

    @Override
    public Result queryById(Integer id) {
        CompetitionParentDO competitionParentDO = competitionParentMapper.selectById(id);
        Boolean hasKey = redisTemplate.hasKey("competitionParent-"+id);
        if(hasKey){
            redisTemplate.opsForValue().increment("competitionParent-"+id);

        }else {
            redisTemplate.opsForValue().set("competitionParent-"+id,1);
        }
        return Result.success(competitionParentDO);
    }
}
